package DAO;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import POJO.Branch;

@Repository
public class BranchDao {

	@Autowired
	JdbcTemplate jdbcTemplate;
	ArrayList<Branch> branches;
	
	public ArrayList<Branch> getAll(){
		branches=new ArrayList<Branch>();
		String getAllBranches="SELECT branch_id,branch_name FROM branch;";
		jdbcTemplate.query(getAllBranches, new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				Branch branch=new Branch();
				branch.setId(rs.getInt("branch_id"));
				branch.setBranchName(rs.getString("branch_name"));
				branches.add(branch);
			}
		});
		return branches;
	}
	
	/**
	 * 根据代理商ID返回设备网点ID以及地址
	 * @param agentId
	 * @return
	 */
	public ArrayList<Branch> getByAgentId(int agentId){
		branches=new ArrayList<Branch>();
		String getAllBranches="SELECT branch_id,branch_addr FROM branch where branch_agent_id = ?;";
		Object[] params=new Object[]{agentId};
		jdbcTemplate.query(getAllBranches,params, new RowCallbackHandler(){
			public void processRow(ResultSet rs) throws SQLException {
				Branch branch=new Branch();
				branch.setId(rs.getInt("branch_id"));
				branch.setAddr(rs.getString("branch_addr"));
				branches.add(branch);
			}
		});
		return branches;
	}
	
	
	/**
	 * 返回网点短信模板
	 * @param branchId
	 * @return
	 */
	public String getMsgTemplate(int branchId){
		String getMsgTemplateSql="SELECT sms_template FROM branch_sms_template where  branch_id=?;";
		String messageTempalte=null;
		Object[] params=new Object[]{branchId};
		try {
			messageTempalte=jdbcTemplate.queryForObject(getMsgTemplateSql, params,String.class);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return messageTempalte;
	}
	
	/**
	 * 查询该网点是否跨区域
	 * @param branchId
	 * @return
	 */
	public int getAcross(int branchId){
		String sql="select branch_isAcross from branch where branch_id=?;";
		int result = 0;
		Object[] params=new Object[]{branchId};
		try {
			result=jdbcTemplate.queryForObject(sql, params,Integer.class);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return result;
	}
}
